from logging import log
import sys,os
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QDialog, QFileDialog, QInputDialog, QLabel, QLineEdit, QMainWindow, QMessageBox, QTabWidget, QTableWidgetItem, QWidget
from PyQt5.QtCore import QCoreApplication, QModelIndex,QTime,Qt,QFile, pyqtPickleProtocol
from PyQt5.QtGui import QIcon, QPixmap
from diagnose import Ui_DiagnoseDia
from login import Ui_loginDia
from mainWindow import Ui_MainWindow
from xlsx import infoXlsxReader
from sql import ImagePathSql, InfoSql
from log import logger
import shutil

#登录窗口
class LoginDia(QtWidgets.QDialog):
    def __init__(self):
        super(QtWidgets.QDialog,self).__init__()
        self.ui = Ui_loginDia()
        self.ui.setupUi(self)
        self.setWindowTitle('登录窗口')
        self.setWindowIcon(QIcon('./icon/医疗箱.png'))
        self.ui.loginButton.clicked.connect(self.onSignIn)
        
    def onSignIn(self):
        username = self.ui.userEdit.text().strip()
        password = self.ui.pwdEdit.text().strip()
        if username == "root" and password == "admin":
            self.mainWin = mainWin()
            self.close()
            self.mainWin.show()
        else:
            self.errMsg = QtWidgets.QMessageBox.critical(self,'错误','用户名或密码输入错误')
            
#诊断弹出窗口
class DiagnoseDia(QtWidgets.QDialog):
    def __init__(self,filePath:str) -> None:
        super(QtWidgets.QDialog,self).__init__()
        self.picFilePath = filePath
        self.ui = Ui_DiagnoseDia()
        self.ui.setupUi(self)
        self.setWindowIcon(QIcon('./icon/医疗箱.png'))
        self.setWindowTitle('患者影像')
        self.setStyleSheet('''QWidget{background:black;}
            QPushButton{background:white;}
            #QDialog{border-image:url(./icon/109375889.jpg)}''')
        
        self.ui.diagButton.clicked.connect(self.diagnoseImg)
    def diagnoseImg(self):
        if self.picFilePath == '':
            QtWidgets.QMessageBox.critical(self,'错误','未选择图片')
            return
        os.system('.\exec_detect.exe.lnk --weights ./best.pt --source {} --view-img '.format(self.picFilePath))        


#主窗口
class mainWin(QtWidgets.QMainWindow):
    def __init__(self):
        super(QtWidgets.QMainWindow,self).__init__()
        self.uiInit()
        self.dataBaseInit()
        self.displayInfoTableFromSql()
        self.displayImgTableFromSql()
        self.connInit()
        
    
    #初始化ui        
    def uiInit(self):
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)    
        self.setWindowIcon(QtGui.QIcon("./icon/医疗箱.png"))    
        self.setWindowTitle('医疗数据诊断系统')
        self.tapWidgetInit()
        self.qssInit()
    #样式初始化
    def qssInit(self):
        qssFile = QFile('./ui/mainWindow.qss')
        qssFile.open(QFile.ReadOnly)
        self.setStyleSheet(qssFile.readAll().data().decode('utf-8'))
        self.ui.picLabel.setStyleSheet('''border-style: solid;
            border-width: 1px;border-color:whitesmoke''')


    #tapWidget初始化
    def tapWidgetInit(self):
        self.ui.tabWidget.setTabText(0,"单张影像诊断")
        self.ui.tabWidget.setTabText(1,"数据批量诊断")

    #初始数据库
    def dataBaseInit(self):
        self.infoSql = InfoSql()   
        self.imgSql = ImagePathSql() 
    
    #初始化槽信号
    def connInit(self):
        #界面切换
        self.ui.infoButton.clicked.connect(self.switch2infoPage)
        self.ui.dignButton.clicked.connect(self.switch2DignPage)
        self.ui.inputButton.clicked.connect(self.switch2InputPage)
        self.ui.searImaButton.clicked.connect(self.switch2SerachImagePage)
        self.ui.picInputButton.clicked.connect(self.switch2InputImagePage)
        #患者数据
        self.ui.insertButton.clicked.connect(self.insertOneRow)
        self.ui.infoTable.cellChanged.connect(self.modifyTable)
        self.ui.deleteButton.clicked.connect(self.delTableRecord)
        self.ui.searchButton.clicked.connect(self.searTableRecord)
        #影像查询
        self.ui.searImaPushButton.clicked.connect(self.searchImage)
        self.ui.imgTable.cellChanged.connect(self.modifyImgTable)
        self.ui.delImage.clicked.connect(self.delImgTable)
        self.ui.insertImgButton.clicked.connect(self.inserOneImg)
        #智能诊断
        self.ui.seleButton.clicked.connect(self.selectPicture)
        self.ui.startDignButton.clicked.connect(self.startDiagnose)
        self.ui.dignSeleXlsxButton.clicked.connect(self.dignSeleXlsx)
        self.ui.startAnaButton.clicked.connect(self.analizeXlsx)
        #数据导入
        self.ui.seleXlsxButton.clicked.connect(self.selectXlsx)
        self.ui.startInpButton.clicked.connect(self.startInput)
        #影像导入
        self.ui.selePicDIr.clicked.connect(self.selectPictureDir)
        self.ui.picStartInpButton.clicked.connect(self.startPicInput)
    #修改数据库
    def modifyTable(self,row,column):
        id = self.ui.infoTable.item(row, 0).text() # 首列为配置名称
        value = self.ui.infoTable.item(row, column).text()
        colName = self.ui.infoTable.horizontalHeaderItem(column).text()

        self.infoSql.modifyOneCell(id,colName,value)

    
    #读取数据库的数据导入到表格
    def displayInfoTableFromSql(self):
        rowLists = self.infoSql.readAllRow()
        for i in range(len(rowLists)):
            self.ui.infoTable.insertRow(i)
            for j in range(len(rowLists[0])):
                item = QTableWidgetItem()
                item.setText(str(rowLists[i][j]))
                self.ui.infoTable.setItem(i,j,item)
    
    #读取数据库的数据导入到图像表格
    def displayImgTableFromSql(self):
        rowLists = self.imgSql.readAllRow()
        for i in range(len(rowLists)):
            self.ui.imgTable.insertRow(i)
            for j in range(len(rowLists[0])):
                item = QTableWidgetItem()
                item.setText(str(rowLists[i][j]))
                self.ui.imgTable.setItem(i,j,item)        
    
    #往表格和数据库插入一条数据
    def insertOneRow(self):
        cnt = self.ui.infoTable.rowCount()
        inputDia = QInputDialog()
        id, okPressed = QInputDialog.getText(self,  "输入病例ID","ID：",QLineEdit.Normal,"")
        if okPressed == False:
            return
        PatientList = self.infoSql.searchOneRow(id) #查询sql中是否存在该数据
        if PatientList == []:
            #插入一条空数据到数据库
            self.infoSql.insertOneNullRow(id)
            PatientList = self.infoSql.searchOneRow(id)
            #将数据插入表格
            self.ui.infoTable.insertRow(cnt)
            self.ui.infoTable.cellChanged.disconnect(self.modifyTable)
            for i in range(len(PatientList)):
                item = QTableWidgetItem()
                item.setText(str(PatientList[i]))
                self.ui.infoTable.setItem(cnt,i,item)
            self.ui.infoTable.cellChanged.connect(self.modifyTable)
            self.ui.infoTable.setCurrentCell(cnt,0)
        else:
            QtWidgets.QMessageBox.critical(self,'错误','该病例已存在')
    
    #删除表格中某个数据
    def delTableRecord(self):
        seleRanges = self.ui.infoTable.selectedRanges()
        for seleRange in seleRanges:
            for i in range(seleRange.rowCount()):
                row = seleRange.topRow() + i
                id = self.ui.infoTable.item(row,0).text()
                self.infoSql.delOneRow(id)
            for i in range(seleRange.rowCount()):
                row = seleRange.topRow()
                self.ui.infoTable.removeRow(row)

    #搜索表格中的数据
    def searTableRecord(self):
        id, okPressed = QInputDialog.getText(self,  "输入病例ID","ID：",QLineEdit.Normal,"")
        print(id)
        if okPressed == False:
            return
        for i in range(self.ui.infoTable.rowCount()):
            if self.ui.infoTable.item(i,0).text() == str(id):
                self.ui.infoTable.setCurrentCell(i,0)

    #根据id号搜索图片
    def searchImage(self):
        id = self.ui.ImagIDEdit.text()
        tmpSql = ImagePathSql()
        row = tmpSql.searchOneRow(id)
        if  row == []:
            QtWidgets.QMessageBox.critical(self,'错误','该病例不存在')
            return
        
        filePath = os.path.abspath('.') + str(row[1]).lstrip('.')
        logger.debug(filePath)
        img = QPixmap(filePath)
        dia = DiagnoseDia(filePath)
        dia.setFixedSize(img.width(),img.height())
        dia.ui.label.setPixmap(img)
        dia.exec()

    #修改影像存储路径
    def modifyImgTable(self,row,column):
        id = self.ui.imgTable.item(row, 0).text() # 首列为配置名称
        value = self.ui.imgTable.item(row, column).text()
        colName = self.ui.imgTable.horizontalHeaderItem(column).text()
        self.imgSql.modifyOneCell(id,colName,value)    
    #插入一条图片数据
    def inserOneImg(self):
        cnt = self.ui.imgTable.rowCount()
        inputDia = QInputDialog()
        id, okPressed = QInputDialog.getText(self,  "输入病例ID","ID：",QLineEdit.Normal,"")
        if okPressed == False:
            return
        PatientList = self.imgSql.searchOneRow(id) #查询sql中是否存在该数据
        if PatientList == []:
            #插入一条空数据到数据库
            self.imgSql.insertOneNullRow(id)
            PatientList = self.imgSql.searchOneRow(id)
            #将数据插入表格
            self.ui.imgTable.insertRow(cnt)
            self.ui.imgTable.cellChanged.disconnect(self.modifyImgTable)
            for i in range(len(PatientList)):
                item = QTableWidgetItem()
                item.setText(str(PatientList[i]))
                self.ui.imgTable.setItem(cnt,i,item)
            self.ui.imgTable.cellChanged.connect(self.modifyImgTable)
            self.ui.imgTable.setCurrentCell(cnt,0)
        else:
            QtWidgets.QMessageBox.critical(self,'错误','该病例已存在')        

    #删除某图像数据
    def delImgTable(self):
        seleRanges = self.ui.imgTable.selectedRanges()
        for seleRange in seleRanges:
            for i in range(seleRange.rowCount()):
                row = seleRange.topRow() + i
                id = self.ui.imgTable.item(row,0).text()
                self.imgSql.delOneRow(id)
            for i in range(seleRange.rowCount()):
                row = seleRange.topRow()
                self.ui.imgTable.removeRow(row)        
    
    #智能诊断：图片诊断
    def startDiagnose(self):
        if self.picFilePath == '':
            QtWidgets.QMessageBox.critical(self,'错误','未选择图片')
            return
        os.system('.\exec_detect.exe.lnk --weights ./best.pt --source {} --view-img '.format(self.picFilePath))

    #智能诊断：选取xlsx文件
    def dignSeleXlsx(self):
        fileDia = QFileDialog()
        filename,selectedDic = fileDia.getOpenFileName()
        self.ui.dignSeleXlsxEdit.setText(filename)     
    def analizeXlsx(self):
        filename = self.ui.dignSeleXlsxEdit.text()
        if filename.rfind('xlsx') != len(filename)-4:
            QtWidgets.QMessageBox.critical(self,'错误','该文件不是xlsx文件,请重新选取')
            self.ui.filePathLineEdit.clear()
            return
        os.system(r'.\setup.exe.lnk {}'.format(filename))
    #选取xlsx文件
    def selectXlsx(self):
        fileDia = QFileDialog()
        filename,selectedDic = fileDia.getOpenFileName()
        self.ui.filePathLineEdit.setText(filename)

    #开始导入
    def startInput(self):
        filename = self.ui.filePathLineEdit.text()
        if filename.rfind('xlsx') != len(filename)-4:
            QtWidgets.QMessageBox.critical(self,'错误','该文件不是xlsx文件,请重新选取')
            self.ui.filePathLineEdit.clear()
            return
        xlsxReader = infoXlsxReader(filename)
        infoLists = xlsxReader.readAllInfo()
        self.ui.pntInfoBrowser.append('开始导入到数据库')
        for i in range(len(infoLists)):
            #获取当前信息
            infoLists[i][0] = str(infoLists[i][0])
            curTime = QTime().currentTime().toString(Qt.ISODate)
            curTime = '[' + curTime + ']:'
            PatientList = self.infoSql.searchOneRow(infoLists[i][0])#查询sql中是否存在该数据
            if PatientList == []:
                #插入数据到数据库
                if self.infoSql.insertOneRow(infoLists[i]) == True:
                    self.ui.pntInfoBrowser.append(curTime + infoLists[i][0] + '病例成功导入到数据库')
                else:
                    self.ui.pntInfoBrowser.append(curTime + infoLists[i][0] + '病例导入失败')
            else:
                self.ui.pntInfoBrowser.append(curTime+ '数据库中已存储该病例：' + infoLists[i][0] )
        
    #对话框选择图片
    def selectPicture(self):
        fileDia = QFileDialog()
        filename,selectedDic = fileDia.getOpenFileName()
        self.ui.picLabel.setPixmap(QtGui.QPixmap(filename))
        self.picFilePath = filename
    
    #对话框选择影像路径
    def selectPictureDir(self):
        fileDia = QFileDialog()
        dir = fileDia.getExistingDirectory()
        self.ui.picDirEdit.setText(dir)

    #开始批量导入影像
    def startPicInput(self):
        dir = self.ui.picDirEdit.text()
        self.ui.picPntInfoBrowse.append('开始导入图片......')
        files = os.listdir(dir)
        for file in files:
            curTime = QTime().currentTime().toString(Qt.ISODate)
            curTime = '[' + curTime + ']:'              
            if file.rfind('jpg') != len(file)-3:
                self.ui.picPntInfoBrowse.append(curTime + '该文件不是jpg格式：' + file)
                continue   
            newDir = '.\images'+'\\' 
            shutil.copy(dir+'/' + file,newDir + file)
            id = file.lstrip('000')
            id = id.rstrip('-rk.jpg')
            tmpList = [id,newDir + file]
            self.imgSql.insertOneRow(tmpList)
            self.ui.picPntInfoBrowse.append(curTime + '成功导入到数据库：' + file)            
        

    #切换到患者数据界面
    def switch2infoPage(self):
        self.ui.stackedWidget.setCurrentIndex(0)
    #切换到智能诊断界面
    def switch2DignPage(self):
        self.ui.stackedWidget.setCurrentIndex(1)
    #切换到数据导入界面
    def switch2InputPage(self):
        self.ui.stackedWidget.setCurrentIndex(2)
    #切换到影像查询界面
    def switch2SerachImagePage(self):
        self.ui.stackedWidget.setCurrentIndex(3)
    #切换到影像导入界面
    def switch2InputImagePage(self):
        self.ui.stackedWidget.setCurrentIndex(4)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    loginDia = LoginDia()
    
    loginDia.show()
    sys.exit(app.exec_())
